package org.andy.shop.controller;


import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.andy.shop.dao.UserInfoMapper;
import org.andy.shop.model.UserInfo;
import org.andy.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value="/user",produces="application/json;charset=UTF-8")
public class UserController {

	@Resource
	private UserService userService;
	
	@Resource
	private UserInfoMapper userMapper;
	
	@PostMapping("/zhuce")
	private String zhuce(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		return json.toJSONString();
	}
	
	@GetMapping("/validUserName")
	@ResponseBody
	private String validUserName(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		UserInfo userInfo = new UserInfo();
		if(StringUtils.isEmpty(request.getParameter("username"))) {
			json.put("result", false);
		}else {
			userInfo.setName(request.getParameter("username"));
			json.put("result", userService.validName(userInfo));
		}
		return json.toJSONString();
	}
	
	@GetMapping("/list")
	@ResponseBody
	private String list(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		Integer rows = null;
		if(StringUtils.isNoneBlank(request.getParameter("pageSize"))) {
			rows = Integer.parseInt(request.getParameter("pageSize"));
		}
		Integer pageNumber = null;
		if(StringUtils.isNoneBlank(request.getParameter("pageNumber"))) {
			pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setName(request.getParameter("name"));
		List<UserInfo> list = userService.list(userInfo, rows, pageNumber);
		Integer total = userMapper.getCount(userInfo);
		json.put("rows", list);
		json.put("total", total);
		return json.toJSONString();
	}
	
	@GetMapping("/detail")
	@ResponseBody
	private String detail(HttpServletRequest request,@RequestParam int id) {
		JSONObject json = new JSONObject();
		UserInfo userInfo = userMapper.selectByPrimaryKey(id);
		json.put("result", true);
		json.put("userInfo", userInfo);
		return json.toJSONString();
	}
	
	@PostMapping("/edit")
	@ResponseBody
	private String edit(HttpServletRequest request,@RequestBody UserInfo userInfo) {
		JSONObject returnJson = new JSONObject();
		userMapper.updateByPrimaryKey(userInfo);
		returnJson.put("result", true);
		return returnJson.toJSONString();
	}
}
